package com.heima.common.exception;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@Configuration
@RestControllerAdvice
public class ExceptionCatch  {

    /**
     * 全局异常处理类  用于捕获未知的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult exception( Exception exception){
        exception.printStackTrace();
        log.error("未知的异常 exception:{} " , exception);
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR ,"您的网络出现了问题, 请稍后重试1");
    }


    @ExceptionHandler(CustomException.class)
    public ResponseResult custException(CustomException customException){
        //打印异常的信息
        customException.printStackTrace();
        log.error("自定义的异常 customException :{}" , customException);

        return ResponseResult.errorResult(customException.getAppHttpCodeEnum());

    }

    /**
     * 参数校验
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleValidationException(MethodArgumentNotValidException ex) {
        log.error("MethodArgumentNotValidException ex:{}", ex);
        ex.printStackTrace();
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, ex.getBindingResult().getFieldError().getDefaultMessage());
    }


}
